﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Marmat.Template.WinForm
{
    public class DocumentViewForm<Entity> : DocumentViewForm<Entity, Entity[]>, IDocumentViewForm<Entity>, IEventHandler<DocumentEventBase>
    {
        Task IEventHandler<DocumentEventBase>.Handler(DocumentEventBase @event)
        {
            Task result = null;
            if (@event.Name == this.Controller.Management.Name)
            {
                Action action = () =>
                {
                    Entity[] data = this.bGridControl1.DataSource as Entity[];
                    for (int i = 0; i < data.Length; i++)
                    {
                        Entity item = data[i];
                        object primaryValue = null;
                        foreach (var member in typeof(Entity).GetMembers())
                        {
                            if (member is FieldInfo field && member.Name == this.Controller.Management.Command.PrimaryName)
                                primaryValue = field.GetValue(item);
                            else if (member is PropertyInfo property && member.Name == this.Controller.Management.Command.PrimaryName)
                                primaryValue = property.GetValue(item);
                        }
                        if (object.Equals(primaryValue, @event.Id))
                        {
                            Entity entity = this.Controller.Management.Command.Load(@event.Id);
                            data[i] = entity;
                        }
                    }
                };
                result = Task.Run(() => this.Invoke(action));
            }
            return result;
        }
    }
}
